package hhm.android.http

import android.text.TextUtils
import com.google.gson.Gson
import hhm.android.library.LogUtils
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.functions.Function

class ResultFunc<T>(var clz: Class<T>) : Function<ResultBean, Observable<T>> {
    override fun apply(res: ResultBean): Observable<T> {
        when (res.isSuccess) {
            -1 -> {//单点登录
                return Observable.error(
                    RequestErrorThrowable(
                        res.isSuccess.toString(),
                        res.message
                    )
                )
            }
            0 -> {//报错
                return if (!TextUtils.isEmpty(res.message)) {
                    Observable.error(RequestErrorThrowable(res.isSuccess.toString(), res.message));
                } else {
                    Observable.error(RequestErrorThrowable(res.isSuccess.toString(), "网络错误"));
                }
            }
            1 -> {
                val data = res.data
                return if (TextUtils.isEmpty(data)) {
                    Observable.just(Gson().fromJson("{}", clz))
                } else {
                    LogUtils.Companion.d("okhttp", ASEJava.aesDecrypt(data))
                    Observable.just(Gson().fromJson(ASEJava.aesDecrypt(data), clz))
                }
            }
            else -> {
                return Observable.error(
                    RequestErrorThrowable(
                        res.isSuccess.toString(),
                        res.message
                    )
                )
            }
        }
    }
}